package cn.ryh.rabbitmq.code.work.fair;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

/**
 * @author Raoyh
 * @Description
 * @create 2022-07-08 17:04
 */
@Slf4j
public class Consumer {


    public static void main(String[] args) {
        // 所有的中间件都是基于TCP/IP协议基础上构建新型的协议规范，只不过rabbitMQ遵循的是AMQP
        // ip port
        // 1、创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.98.34.119");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("admin");
        factory.setPassword("XXXXXXX");
        Connection connection = null;
        Channel channel = null;
        //获取队列的名称
        final String queueName =  "work-queue";
        try {
            // 2、创建连接Connection
            connection = factory.newConnection("消费者");
            // 3、通过连接创建通道Channel
            channel = connection.createChannel();
            // 5、定义接受消息的回调
            channel.basicQos(10);
            Channel finalChannel = channel;
            channel.basicConsume(queueName, false,
                    (consumerTag, message) -> {
                        log.info("收到的消息是：{}", new String(message.getBody(), StandardCharsets.UTF_8));
                        try {
                            Thread.sleep(2000);
                            finalChannel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    },
                    consumerTag ->
                            log.info("获取失败"));
            log.info(queueName + "：开始接受消息");
            System.in.read();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(channel) && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException | TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if (Objects.nonNull(connection)) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
